//
//  RBDatePickerView.m
//  自定义日期选择器
//
//  Created by RaoBo on 2017/4/9.
//  Copyright © 2017年 RaoBo. All rights reserved.
//

#import "RBDatePickerView.h"

#define RB_Screen_W [UIScreen mainScreen].bounds.size.width
#define RB_Screen_H [UIScreen mainScreen].bounds.size.height

@interface RBDatePickerView () <UIPickerViewDelegate,UIPickerViewDataSource>
{
    NSInteger _yearSelectedRow;
    NSInteger _monthSelectedRow;
    NSInteger _daySelectedRow;
    
    NSString *_selectedYearTitle;
    NSString *_selectedMonthTitle;
    NSString *_selectedDayTitle;
    
    CGRect _pickerViewFrame;
    
    // 注意此处写的是带下划线的实例变量，用调用getter 方法才有效
    NSMutableArray *_yearArray;
    NSMutableArray *_monthArray;
    NSMutableArray *_dayArray; //  [[self dayArray] count]
}

@property (nonatomic, strong) UIPickerView *pickerView; // 日期选择器

@property (nonatomic, strong) UIView *topView; // 顶部视图
@property (nonatomic, strong) UIButton *cancelBtn; // 取消按钮
@property (nonatomic, strong) UIButton *sureBtn; // 确定按钮
@property (nonatomic, strong) UILabel *chooseDateLB;//选择日期

@end

// 常量
static const CGFloat topView_H = 38;
static const CGFloat button_W = 60;
static const CGFloat choseLable_W = 100; // 选择日期label 的宽
static const CGFloat animationDuration = 0.3;
static const NSInteger buttonFontSize = 18;

// 枚举
typedef enum : NSUInteger {
    RBComponentTypeYear = 0, // 年
    RBComponentTypeMonth,    // 月
    RBComponentTypeDay,      // 日
} RBComponentType;


@implementation RBDatePickerView

- (instancetype)init
{
    self = [super init];
    if (self) {
        self = [self initWithFrame:CGRectMake(0, 0, RB_Screen_W, 150)]; // 这样写 什么意思？？
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self rb_initData:frame];
        [self rb_initSubViews];
    }
    return self;
}

// 初始化子视图
- (void)rb_initSubViews {
    [self addSubview:self.topView];
    [self.topView addSubview:self.cancelBtn];
    [self.topView addSubview:self.chooseDateLB];
    [self.topView addSubview:self.sureBtn];
    
    [self addSubview:self.pickerView];
}
#pragma mark 1. lazy get

- (UIView *)topView {
    if (!_topView) {
        _topView = [[UIView alloc] initWithFrame:CGRectMake(0, RB_Screen_H, RB_Screen_W, topView_H)];
        _topView.backgroundColor = [UIColor orangeColor];
    }
    return _topView;
}

- (UIPickerView *)pickerView {
    if (!_pickerView) {
        _pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_topView.frame), RB_Screen_W, _pickerViewFrame.size.height)];
        
        //代理
        _pickerView.delegate = self;
        _pickerView.dataSource = self;
        
        _pickerView.backgroundColor = [UIColor colorWithRed:244.0/255 green:244.0/255 blue:244.0/255 alpha:1];
    }
    return _pickerView;
}
// 取消button
- (UIButton *)cancelBtn {
    if (!_cancelBtn) {
        _cancelBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        _cancelBtn.frame = CGRectMake(0, 0, button_W, topView_H);
        [_cancelBtn setTitle:@"取消" forState:(UIControlStateNormal)];
        [_cancelBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        [_cancelBtn.titleLabel setFont:[UIFont systemFontOfSize:buttonFontSize]];
        [_cancelBtn addTarget:self action:@selector(cancelButtonClicked:) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _cancelBtn;
}

// 确定按钮
- (UIButton *)sureBtn {
    if (!_sureBtn) {
        _sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _sureBtn.frame = CGRectMake(self.frame.size.width - button_W, 0, button_W, topView_H);
        [_sureBtn setTitle:@"确定" forState:(UIControlStateNormal)];
        [_sureBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        [_sureBtn.titleLabel setFont:[UIFont systemFontOfSize:buttonFontSize]];
        [_sureBtn addTarget:self action:@selector(sureButtonClicked:) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _sureBtn;
}

// 选择日期label
- (UILabel *)chooseDateLB {
    if (!_chooseDateLB) {
        _chooseDateLB = [[UILabel alloc] initWithFrame:CGRectMake((RB_Screen_W - 100) / 2, 0, choseLable_W, topView_H)];
        _chooseDateLB.font = [UIFont systemFontOfSize:buttonFontSize];
        _chooseDateLB.textColor = [UIColor whiteColor];
        _chooseDateLB.text = @"选择日期";
        _chooseDateLB.textAlignment = NSTextAlignmentCenter;
    }
    return _chooseDateLB;
}

#pragma mark  2. button 点击事件
- (void)cancelButtonClicked:(UIButton *)sender {
    [self rb_dismiss];
}

- (void)sureButtonClicked:(UIButton *)sender {
  // 取出当前选择的年 月 日
    _selectedYearTitle = [self pickerView:_pickerView titleForRow:_yearSelectedRow forComponent:RBComponentTypeYear];
    _selectedMonthTitle = [self pickerView:_pickerView titleForRow:_monthSelectedRow forComponent:RBComponentTypeMonth];
    _selectedDayTitle = [self pickerView:self.pickerView titleForRow:_daySelectedRow forComponent:RBComponentTypeDay];
    
    NSLog(@"选择的日期是:%@%@%@",_selectedYearTitle,_selectedMonthTitle,_selectedDayTitle);

    if (self.sureButtonClickBlock) {
        // 把选择的日期传出去
        self.sureButtonClickBlock(_selectedYearTitle, _selectedMonthTitle, _selectedDayTitle);
    }
    [self rb_dismiss];
}

// 设置默认日期
- (void)rb_setUpDefaultDateWithYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day {
    
    NSString *yearStr = [NSString stringWithFormat:@"%ld",year];
    NSString *monthStr = [NSString stringWithFormat:@"%ld",month];
    NSString *dayStr = [NSString stringWithFormat:@"%ld",day];
    
    _yearSelectedRow = [_yearArray indexOfObject:yearStr];
    _monthSelectedRow = [_monthArray indexOfObject:monthStr];
    _daySelectedRow = [[self dayArray] indexOfObject:dayStr];
    
    [self.pickerView selectRow:_yearSelectedRow inComponent:RBComponentTypeYear animated:NO];
    [self.pickerView selectRow:_monthSelectedRow inComponent:RBComponentTypeMonth animated:NO];
    [self.pickerView selectRow:_daySelectedRow inComponent:RBComponentTypeDay animated:NO];
}

#pragma mark 3. 设置年 月 日
// 初始化数据
- (void)rb_initData:(CGRect)frame {
    
    _pickerViewFrame = frame;
    
    self.frame = CGRectMake(0, 0, RB_Screen_W, RB_Screen_H);
    self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3]; // 黑色透明
    
    _yearSelectedRow = 0;
    _monthSelectedRow = 0;
    _daySelectedRow = 0;
    
    [self setUpYMDateDic];
}

// 初始化年月数据
- (void)setUpYMDateDic {
    _yearArray = [NSMutableArray arrayWithCapacity:0];
    _monthArray = [NSMutableArray array];
    
    // 年
    for (NSInteger i = 1950; i <= 2050; i++) {
        [_yearArray addObject:[NSString stringWithFormat:@"%ld",(long)i]];
    }
    
    // 月:记住没有 0 月
    for (NSInteger i = 1; i <= 12; i++) {
        [_monthArray addObject:[NSString stringWithFormat:@"%ld",(long)i]];
    }
}

// 获取每月天数 日
- (NSMutableArray *)dayArray {
    _dayArray = [NSMutableArray arrayWithCapacity:0];
    NSInteger year = [[_yearArray objectAtIndex:_yearSelectedRow] integerValue];
    NSInteger month = [[_monthArray objectAtIndex:_monthSelectedRow] integerValue];
    NSInteger maxDay = 31;
    if (year % 400 == 0 && month == 2) {
        maxDay = 29;
    } else if ((year % 100 != 0) && (year % 4 == 0) && month == 2){
        maxDay = 29;
    } else if (month == 2){
        maxDay = 28;
    } else if ((month % 2 != 0 && month < 8) || month == 8 || (month % 2 == 0 && month > 8)){
        maxDay = 31;
    } else {
        maxDay = 30;
    }
    for (NSInteger i = 1; i <= maxDay; i++) {
        [_dayArray addObject:[NSString stringWithFormat:@"%ld",(long)i]];
    }
    return _dayArray;
}

#pragma mark show dismiss
- (void)rb_show {

    [[UIApplication sharedApplication].keyWindow addSubview:self];
    
    [UIWindow animateWithDuration:animationDuration animations:^{
        CGRect tempRect = _topView.frame;
        tempRect.origin.y = RB_Screen_H - topView_H - _pickerViewFrame.size.height;
        _topView.frame = tempRect;
        
        tempRect = _pickerViewFrame;
        tempRect.origin.y = CGRectGetMaxY(_topView.frame);
        _pickerView.frame = tempRect;
    }];
}

- (void)rb_dismiss {
    [UIView animateWithDuration:animationDuration animations:^{
        CGRect tempRect = _topView.frame;
        tempRect.origin.y = RB_Screen_H;
        _topView.frame = tempRect;
        
        tempRect.origin.y = CGRectGetMaxY(_topView.frame);
        _pickerView.frame = tempRect;
        
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

#pragma mark -- UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 3;
}

// 返回每个component 的个数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    switch (component) {
        case RBComponentTypeYear:
            return _yearArray.count;
            break;
        case RBComponentTypeMonth:
            
            return _monthArray.count;
            
            break;
        case RBComponentTypeDay:
            
            // 注意这里用的是 带下划线的实例变量，需要掉getter方法，才有值
//            NSLog(@"%@",[self dayArray]);
            return [self dayArray].count;
//            NSLog(@"%ld",_dayArray.count);
//            return _dayArray.count;
            break;
        default:
            return _monthArray.count;
            break;
    }
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    switch (component) {
        case RBComponentTypeYear:
            return _yearArray[row];
            break;
        case RBComponentTypeMonth:
            return _monthArray[row];
            break;
        case RBComponentTypeDay:
            return _dayArray[row];
            break;
        default:
            return _monthArray[row];
            break;
    }
}

// 点击了row
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    
    // 获取当前year，month，day 在数组中的indexPath
    NSString *year = [self systemYearStr];
    NSString *month = [self systemMonthStr];
    NSString *day = [self systemDayStr];
    
    // 获取在数组中的index:注意类型
    NSUInteger yearIndex = [_yearArray indexOfObject:year];
    NSUInteger monthIndex = [_monthArray indexOfObject:month];
    NSUInteger dayIndex = [_dayArray indexOfObject:day];
    
    switch (component) {
        case RBComponentTypeYear:
        {
            _yearSelectedRow = row;
            if (_yearSelectedRow > yearIndex) {
                _yearSelectedRow = yearIndex; // 重新赋值
                
                // 滚到当前year
                [pickerView selectRow:_yearSelectedRow inComponent:0 animated:YES];
                
                
                if (_monthSelectedRow > monthIndex) {
                    _monthSelectedRow = monthIndex;
                    [pickerView selectRow:_monthSelectedRow inComponent:1 animated:YES];
                }
                
                if (_daySelectedRow > dayIndex) {
                    _daySelectedRow = dayIndex;
                    [pickerView selectRow:_daySelectedRow inComponent:2 animated:yearIndex];
                }
            }
            
            // 第二种情况:先是year<今年,之后month>今月 。自动回到今天
            if ((_yearSelectedRow >= yearIndex) && (_monthSelectedRow >= monthIndex)) {
                // 重新赋值
                _yearSelectedRow = yearIndex;
                _monthSelectedRow = monthIndex;
                
                // 滚回去
                [pickerView selectRow:_yearSelectedRow inComponent:0 animated:YES];
                [pickerView selectRow:_monthSelectedRow inComponent:1 animated:YES];
            }
            
            // 第三种情况:先是year<今年,之后month>=今月,day>= 今天; 之后修改了year>今年。 自动回到今天
            if ((_yearSelectedRow >= yearIndex) && (_monthSelectedRow >= monthIndex) && (_daySelectedRow >= dayIndex)) {
                
                // 重新赋值
                _yearSelectedRow = yearIndex;
                _monthSelectedRow = monthIndex;
                _daySelectedRow = dayIndex;
                
                // 滚回去
                [pickerView selectRow:_yearSelectedRow inComponent:0 animated:YES];
                [pickerView selectRow:_monthSelectedRow inComponent:1 animated:YES];
                [pickerView selectRow:_daySelectedRow inComponent:2 animated:YES];
            }
        }break;
            
        case RBComponentTypeMonth:{
            _monthSelectedRow = row; // 初始值
            // year > && month >
            if ((_yearSelectedRow >= yearIndex) && (_monthSelectedRow > monthIndex)) {
                _yearSelectedRow = yearIndex;
                _monthSelectedRow = monthIndex;
                [pickerView selectRow:_monthSelectedRow inComponent:1 animated:YES];
            }
            
            // 判断今年、今月、今天
            // eg:今年-今月->今天
            if ((_yearSelectedRow >= yearIndex) &&(_monthSelectedRow >= monthIndex) && (_daySelectedRow > dayIndex)) {
                _daySelectedRow = dayIndex;
                [pickerView selectRow:_daySelectedRow inComponent:2 animated:YES];
            }
        }break;
            
        case RBComponentTypeDay:{
            _daySelectedRow = row;
            if ((_yearSelectedRow >= yearIndex) && (_monthSelectedRow >= monthIndex) && (_daySelectedRow > dayIndex)) {
                _yearSelectedRow = yearIndex;
                _monthSelectedRow = monthIndex;
                _daySelectedRow = dayIndex;
                [pickerView selectRow:_yearSelectedRow inComponent:0 animated:YES];
                [pickerView selectRow:_monthSelectedRow inComponent:1 animated:YES];
                [pickerView selectRow:_daySelectedRow inComponent:2 animated:YES];
            }
        }break;
            
        default:
            _yearSelectedRow = row;
            break;
    }
    
    [pickerView reloadAllComponents];
}

//  返回component 的 宽
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    
    return self.frame.size.width / 3; // 3 等分
}

// 有点像cellForRow 方法
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    
    UILabel *pickerLB = (UILabel *)view;
    if (!pickerLB) {
        pickerLB = [[UILabel alloc] init];
        pickerLB.adjustsFontSizeToFitWidth = YES;
        [pickerLB setTextAlignment:NSTextAlignmentCenter];
        [pickerLB setBackgroundColor:[UIColor clearColor]];
        
        [pickerLB setFont:_titleFont ? _titleFont : [UIFont systemFontOfSize:16]];
    }
    
    pickerLB.text = [self pickerView:pickerView titleForRow:row forComponent:component];
    
    return pickerLB;
}
#pragma mark 工具方法，获取系统时间
// 获取系统时间
-(NSArray*)getsystemtime{
    
    NSDate *date = [NSDate date];
    NSTimeInterval  sec = [date timeIntervalSinceNow];
    NSDate *currentDate = [[NSDate alloc]initWithTimeIntervalSinceNow:sec];
    NSDateFormatter *df = [[NSDateFormatter alloc]init];
    [df setDateFormat:@"yyyy-MM-dd"];
    NSString *na = [df stringFromDate:currentDate];
    
    //截取后的字符串
    NSArray *cutArr = [na componentsSeparatedByString:@"-"];
    return cutArr;
}
// 获取year
- (NSString *)systemYearStr{
    
    NSArray *tempArr = [self getsystemtime];
    
    NSString *year;
    // 年 月 日 数组元素个数应该是3
    if (tempArr.count == 3) {
        year = tempArr[0];
    }
    
//        NSLog(@"%@",[NSString stringWithFormat:@"%@年",year]);
    return [NSString stringWithFormat:@"%@",year];
}
// 获取month  02月 两个数,特殊化,该方法有待优化
- (NSString *)systemMonthStr {
    
    if ([self getsystemtime]) {
        NSString *month = [self getsystemtime][1]; //取数组第二个元素
        
        NSMutableArray *tempArr = [NSMutableArray array];
        for (int i = 0; i < month.length; i++) {
            // 切割
            NSString *letter = [month substringWithRange:NSMakeRange(i, 1)];
            [tempArr addObject:letter];
        }
        NSInteger decade = [tempArr[0] integerValue]; // 十位数
        NSInteger unit = [tempArr[1] integerValue]; // 个位数
        
        // 02 = 0*10 + 2 ;  31 = 3*10 + 1
        NSInteger sum = decade * 10 + unit;
        
//                NSLog(@"%@",[NSString stringWithFormat:@"%ld月",sum]);
        return [NSString stringWithFormat:@"%ld",(long)sum];
    }else {
        return @"1";
    }
}
// 获取day
- (NSString *)systemDayStr {
    
    NSString *day = [self getsystemtime][2];
    
    // 截取
    NSMutableArray *tempArr = [NSMutableArray array];
    for (int i = 0; i < day.length; i++) {
        NSString *str =  [day substringWithRange:NSMakeRange(i, 1)];
        [tempArr addObject:str];
    }
    
    NSInteger decade = [tempArr[0] integerValue];
    NSInteger unit = [tempArr[1] integerValue];
    
    NSInteger result = decade * 10 + unit;
//        NSLog(@"%@",[NSString stringWithFormat:@"%ld日",result]);
    
    return [NSString stringWithFormat:@"%ld",(long)result];
}

@end
